package com.stylefeng.guns.modular.system.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stylefeng.guns.common.persistence.model.Filemeta;
import com.stylefeng.guns.common.persistence.dao.FilemetaMapper;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.modular.system.service.IFilemetaService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2021-01-17
 */
@Service
public class FilemetaServiceImpl extends ServiceImpl<FilemetaMapper, Filemeta> implements IFilemetaService {

	/**
	 * 上传文件
	 */
	@Override
	public Filemeta uploadFile(MultipartFile file, String destdir,HttpServletRequest request, HttpServletResponse response) {
		ShiroUser user = ShiroKit.getUser();
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
//		System.out.println("scheme="+request.getScheme());//http
//		System.out.println("serverName="+request.getServerName());/localhost
//		System.out.println("serverPort="+request.getServerPort());//8089
//		System.out.println("basePath="+basePath);//http://localhost:8089
		String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\";
		System.out.println("uploadPath="+uploadPath);
		try {
	         //上传文件过程
                String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                File destFile = new File(uploadPath + destdir);
                if (!destFile.exists()) {
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew() + "." + suffix;//后缀名
                String temporaryFileUrl = destFile.getAbsoluteFile() + File.separator + fileNameNew;
                File f = new File(temporaryFileUrl);
                //如果当前文件已经存在了，就跳过。
                if(f.exists()){
                	return null;
                }
                f.createNewFile();
                //获取上传文件流
                InputStream in=file.getInputStream();
//                使用 FileOutputStream打开服务器端的上传文件
                FileOutputStream out=new FileOutputStream(f);
//                流的对拷
                byte[] bytes=new byte[1024];//每次读取一个字节
                int len;
//                开始读取上传文件的字节，并将其输出到服务器端的上传文件输出流中
                while ((len=in.read(bytes))>0)
                    out.write(bytes,0,len);
                in.close();
                out.close();

                Filemeta filemeta = new Filemeta();
                filemeta.setFileName(file.getOriginalFilename());
                filemeta.setFileSize(file.getSize());
                filemeta.setFileType(file.getContentType());
                filemeta.setFileUrl(("/static/"+ destdir+File.separator + fileNameNew).replace("\\", "/"));
                filemeta.setUserId(user.getId());
                filemeta.setTemporaryFileUrl(temporaryFileUrl);
                this.insert(filemeta);//保存文件信息
                return filemeta;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
     * 为文件重新命名，命名规则为当前系统时间毫秒数
     * @return string
     */
    private String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }
	
}
